<?php 
session_start();
require_once ("class/m_product.php");
require_once ("class/m_customer.php");
require_once ("class/m_main.php");
require_once ("class/m_stock.php");
require_once ("class/m_card_coupon.php");
require_once ("class/m_login.php");
require_once ("class/m_report.php");
	$m_pro = new M_product();
	$m_cust= new M_customer();
	$m=new M_main();
	$m_report=new M_report();
	$m_stock=new M_stock();
	$m_login = new M_login();
	$m_coupon=new M_card_coupon();
	
	if (isset($_POST['m'])  &&  $_POST['m']!=""){
		// from dialog search customer
		if ($_POST['m']== 's_cust'){
			$ar_val=$_POST['var'];
			
			//return result;
			$result=$m_cust->getData($ar_val['name'],$ar_val['code']);
			//row count
			$rows=$result->RecordCount();
			$html="";
			$r=1;
			if ($rows>0){
				while($row = $result->FetchRow()){
					$html .="<tr>"
						."<td align='right'>".$r."</td>"
						."<td align='right' style='display:none;'>".$row["ID"]."</td>"
						."<td align='center'>".$row["Code"]."</td>"
						."<td align='left'>".$row["FirstName"].' '.$row["LastName"]."</td>"
						."<td align='center'>".$row["BirthDay"]."</td>"
						."<td align='center'>".$row["Telephone"]."</td>"
						."<td align='center'>".$row["LastedAccess"]."</td>"
						."<td align='center'><img src='images/success.png' style='cursor:pointer' id='btnSelectCust' title='Select Customer' border=0/></td>"
						."</tr>";			
					$r++;
				}
			}else{
				$html= "<tr><td colspan='7' style='align:center;font-weight:bold;color:red'>Not found</td></tr>";
			}
			$re=array('data'=>$html,
					'rows'=>$rows
					);			
			echo json_encode($re);

		}else if ($_POST['m']== 'chkRm'){			
			$custid = $_POST['custid'];
			$_SESSION['custid'] = $_POST['custid'];
			$rst = $m->getCreditSaleRemain($custid);
			$msg="0";
		
			// Credit Sale remain
			if ($rst['remainAmt'] != '0'){
					$msg=number_format($rst['remainAmt'] ,'2','.',',');
			}

			if ($rst['serviceCnt'] != '0'){
				$r=1;
				$html="";
				foreach($rst['servicelst'] as $val){ 
					$html .="<tr>"
					."<td align='right'>".$r."</td>"
					."<td align='left'>".$val["ProductName"]."</td>"
					."<td align='right'>".$val["Remain"]."</td>"
					."<td align='center'>".$val["ExpireDate"]."</td>"
					."</tr>";			
					$r++;
				} 
			}
			
			$re=array('remain'=>$msg
					,'sCnt'=>$rst['serviceCnt']
					,'data' => $html);

			echo json_encode($re);

		}else if ($_POST['m']== 'cust2'){
			$ar_val=$_POST['var'];
			
			//return result;
			$result=$m_cust->getData2($ar_val['name'],$ar_val['code'],null,null,null,null,1,$ar_val['cardid']);

			//row count
			$rows=$result->RecordCount();
			$html="";
			$r=1;
			if ($rows>0){
				while($row = $result->FetchRow()){
					$html .="<tr>"
						."<td align='right'>".$r."</td>"
						."<td align='right' style='display:none;'>".$row["ID"]."</td>"
						."<td align='center'>".$row["Code"]."</td>"
						."<td align='left'>".$row["FirstName"].' '.$row["LastName"]."</td>"
						."<td align='center'>".$row["BirthDay"]."</td>"
						."<td align='center'>".$row["CardID"]."</td>"
						."<td align='center'>".$row["Telephone"]."</td>"
						."<td align='center'>".$row["LastedAccess"]."</td>"
						."<td align='center'><img src='images/success.png' style='cursor:pointer' id='btnSelectCust' title='Select Customer' border=0/></td>"
						."</tr>";			
					$r++;
				}
			}else{
				$html= "<tr><td colspan='8' style='align:center;font-weight:bold;color:red'>Not found</td></tr>";
			}
			$re=array('data'=>$html,
					'rows'=>$rows
					);			
			echo json_encode($re);		

		}else if ($_POST['m']=='checkstock'){
			$list=$_POST['list'];
			$arr=array();
			/*foreach($list as $val){
				if ($val['type']==1) {
					$sql = " Select t.ID, CASE WHEN Scale=0 or Scale IS NULL or Scale ='' THEN 1 ELSE Scale END * ".$val['amt']." as Amount
						 FROM  tb_product t  where t.ID =".$val['pid'];
					
					$result = $m->ExecuteData($sql);
					$row=$result->FetchRow();	 
					if (array_key_exists($row['ID'] , $arr)){
						$arr[$row['ID']] = $arr[$row['ID']]+ $row['Amount'] ;
					}else{
						$arr[$row['ID']]=$row['Amount'] ;
					}
				}
				else if ($val['type']==2 || $val['type']==3){
					$sql=" select d.SubProductID as ID , d.Amount*".$val['amt'] ." as Amount
						from tb_product p left join tb_product_details d on d.ProductID=p.ID
						where p.ID=".$val['pid'];
						
					$result = $m->ExecuteData($sql);
					while ($row=$result->FetchRow()){
						if (array_key_exists($row['ID'] , $arr)){
							$arr[$row['ID']] = $arr[$row['ID']]+ $row['Amount'] ;
						}else{
							$arr[$row['ID']]=$row['Amount'] ;
						}						
					}
				}
				// else if ($list['type']==4){
					// $sql = "select  pp.ID , Sum(ds.Amount) as Amount
							// from tb_product p
							// left JOin tb_product_details d on d.ProductID=p.ID
							// left join tb_product ps on ps.ID = d.SubProductID
							// left join tb_product_details ds on ds.ProductID=ps.ID
							// left join tb_product pp on pp.ID = ds.SubProductID
							// where p.ID=".$list['pid']." Group by pp.ID ";
					
					// $result = $this->ExecuteData($sql);
					// while ($row=$result->FetchRow()){
						// if (array_key_exists($row['ID'] , $arr)){
							// $arr[$row['ID']] = $arr[$row['ID']]+ $row['Amount'] ;
						// }else{
							// $arr[$row['ID']]=$row['Amount'] ;
						// }						
					// }
				// }
			}
			$rows['result']=1;
			foreach ( $arr as $key=>$value ){
				$sql = " select p.ProductName , coalesce(s.Amount ,0) as Amount , u.Unit
						from tb_product  p 
						left join tb_stock_product s  on p.ID=s.ProductID and s.BranchID=".$_SESSION['bid']." and s.Amount >= ".$value ."
						 join tb_units u on u.ID= CASE WHEN p.SubUnit='' or p.SubUnit=0 Then p.MainUnit else p.SubUnit End
						where p.IsDeleted=0 and  p.ID=".$key ;
						
				$result = $m->ExecuteData($sql);
				$rows=$result->FetchRow();
				
				if ($rows['Amount'] > 0){
					$rows['result']=1;
				}else{
					$rows['result']=0;
					break;
				}
				
			}*/
			$rows['result']=1;
			$rows['Amount']=0;
			echo json_encode( $rows );
		
		}else if ($_POST['m']== 's_prod'){
				$id=$_POST['proID'];	
				$type=$_POST['type'];
				$amt=$_POST['amt'];
	 
				$result=$m_pro->getData(null,0,0,1,$id);
				
				$rows=$result->RecordCount();
				$value=$result->FetchRow();
		 
				echo json_encode($value);		

		}
		else if  ($_POST['m']== 'add'){
				//array
				$list=$_POST['v'];
				$paylist=$_POST['p'];
				
				$var="";
				$user=$_SESSION['username'];	
				
				foreach($list as $var){;}
				
				$arProduct=$var['productlist'];
				$arrList=$var;
				$arrList['Branch']=$_SESSION['bid'];
				$arrList['SaleDate']=date( "Y/m/d H:i:s" );
				$arrList['SaleBy'] =$user;
				
				$no=$m->getLastBillNo($_SESSION['bid']);
				$arrList['BillNo']=$no;
				
				if ($arrList['CustID']=="1"){
					$custId = $_SESSION['custid'];
				}else{ 
					$custId = 0;
				}	
				
				$arrList['CustID'] = $custId;
				
				//$custId=$arrList['CustID'];
				if ($arrList['IsExtraDiscount']=='1'){
					$premium_id=$m->getPremiumID($arrList['ExID']);
					// Comment by xxx
					//$m_stock->UpdateReturnStockBranch( $premium_id , $_SESSION['bid'] , 1 , $user, 0);	  
				}
				//Insert data
				$id=$m->InsertData($arrList);
				
				if ($id !=0) {
				
					$sql=" Insert into tb_pos_detail(Pos_id ,  Product , Amount, Price , Total, Discount) values ";
					$sqlDetail="";	
					
					foreach($arProduct as $val){
						$sqlDetail .=",(".$id.",". $val['Product'].",".$val["Amount"].",".$val["Price"].",".$val["Total"].",".$val["Discount"]." )";
						
						//Course
						if ($val['Type']==4){
							 $m->InsertService($id, $custId ,$val['Product'],$_SESSION['bid'], $val["Total"],$val["Amount"] * $val['Times'],$user);
						}
						//Product
						else if ($val['Type']==1){
							//Update stock
							//$m_stock->UpdateReturnStockBranch($val['Product'] , $_SESSION['bid'] ,$val["Amount"] , $user, 0);
						}else if ($val['Type']==2 || $val['Type']==3){
							//$m_stock->Stock_Set_Treatment_Update($val['Product'] , $_SESSION['bid'] ,$val["Amount"] , $user, 0);
						}
					} 			
				
					//remove first comma
					$sqlDetail = substr($sqlDetail,1);
					//Insert data
					$m->Excute($sql.$sqlDetail);							
					
					$sqlPay=" Insert into tb_pos_payment(Pos_id ,  PaymentType , PaymentAmount,CardNo) values ";
					$sqlPayDetail='';
					
					foreach ($paylist as $pay){
						$sqlPayDetail .=",(".$id.",'". $pay['PaymentType']."',".$pay["PaymentAmount"].",'".$pay["CardNo"]."')";
					}
					
					//remove first comma
					$sqlPayDetail = substr($sqlPayDetail,1);
					//Insert data to payment detail 
					$m->Excute($sqlPay.$sqlPayDetail);	
					
					//update last access
					if ($custId != 0){
						$m->updateLastAccess($custId);
					}
					//Credit Sale  
					// User just pay 1 time , if user pay more than 2 time, creditsale must never been occur
					if ($arrList["IsCreditSale"]=="1"){
						$q = $m->InsertCreditSale($arrList,$id,$user,$pay['PaymentType'],$pay["CardNo"]);
					}
					//print $q;
					$arr=array('info'=>'Completed',
								'id'=>$id
						);
					echo json_encode($arr);///$sql.$sqlDetail ;	
				
				}else{
					//print $q;
					$arr=array('info'=>'Error',
								'id'=>$id
						);
					echo json_encode($arr);///$sql.$sqlDetail ;	
				}
		}
		else if  ($_POST['m']== 'pos_history'){
			
			$datefrom = $_POST['datefrom'];
			$dateto = $_POST['dateto'];
			
			if ($_SESSION['branchtype'] =="1")
				$branchid=$_POST['barnchid'];
			else 
				$branchid=$_SESSION['bid'];
			
			if (isset($datefrom) && $datefrom  !=""){
				list($day, $month, $year) = split('/', $datefrom);
				$dfrom= $year."/".$month."/".$day;
				list($day, $month, $year) = split('/', $dateto);
				$dto= $year."/".$month."/".$day;
			}
			$page=$_POST['page'];
			$page=isset($page)?$page:1;
			
			$result=$m->getHistoryData($branchid,$page,$dfrom, $dto);
			$rows=$m->getRowCount();
			$i=1 + (($page-1) * $m->getListPage());
			$html="";
			
			if($rows>0){
				while($row = $result->FetchRow()){
					if ($row['flag']=='1'){
						$style="style='color:red'  title='Cancel Bill' ";
					}else{
						$style='';
					}
					If($i%2 <> 0){
						$html .= "<tr class=row1 ".$style.">";
					} else{
						$html .= "<tr ".$style.">";    
					}
					$html .= genHitoryTable($row,$i)."</tr>";
					$i++;
				}
			}else{
				$html="<tr>"
					."<td colspan='11' align='center' ><img src='./images/info.gif'/><b/></td>"
					."</tr>";
			}			
	
			//Return result , rows , page
			$ar_result=array('data'=>$html,
							'rows'=>$rows,
							'totalpage'=>$m->getTotalPage());
			echo json_encode( $ar_result );		
			
		}else if ($_POST['m']=='check_ex_discount'){
			//$toalAmt=$_POST['total'];
			$result= $m->checkSpecialDiscount();

			echo json_encode( $result );
			
		
		}else if  ($_POST['m']== 'pos_history_d'){
			$date=$_POST['date'];
			$branhid=$_POST['branch'];
			$type=$_POST['type'];
			$page=$_POST['page'];
			
			$page=isset($page)?$page:1;
			$resultHeader =$m->getHistoryData($branhid,$page,$date, $date);
			
			$result=$m->getHistoryDetail($branhid , $date, $type , $page);
			//echo $result;
			$rows=$m->getRowCount();
			$i=1 + (($page-1) * $m->getListPage());
			$html="";
			
			if($rows>0){
				while($row = $result->FetchRow()){
					if ($type=='customer'){
						$ar = $m->getPaymentHistory($row['CustID'],$branhid , $date);
					}
					If($i%2 <> 0){
						$html .= "<tr class=row1>";
					} else{
						$html .= "<tr>";    
					}
					$html .= genHitoryDetail($row,$i,$type,$ar )."</tr>";
					$i++;
				}
			}else{
				$html="<tr>"
					."<td colspan='8' align='center' ><img src='./images/info.gif'/><b/></td>"
					."</tr>";
			}			
			$rowHeader=$resultHeader->FetchRow();
			//Return result , rows , page
			$ar_result=array('data'=>$html,
							'rows'=>$rows,
							'date'=> $rowHeader['SaleDate1'] ,
							'branch'=>$rowHeader['BranchName'],
							'amount'=>  number_format( $rowHeader['Amount'] ,'2','.',',') ,
							'payment'=> number_format( $rowHeader['Payment'] ,'2','.',',') ,
							'remain'=>number_format( $rowHeader['Remain'] ,'2','.',',')  ,
							'totalpage'=>$m->getTotalPage());
			echo json_encode( $ar_result );		
			
		}else if ($_POST['m']=="checkuser"){
			$userName=$_POST['uname'];
			$password=$_POST['pwd'];			
			$IsCompleted = $m_login->checkUserLogin($userName,$password);
			echo $IsCompleted ;
		}
	}else{
			if (isset($_GET['c']) && $_GET['c'] !="" ){
				echo json_encode( $m_pro->getDataCBO($_GET['c']));
			}else if (isset($_GET['cval'] ) && $_GET['cval'] !=""){
				echo json_encode($m_coupon->getDataDetail($_GET['cval']));
			}else if (isset($_GET['cy']) && $_GET['cy'] !="" ){
				echo json_encode( $m_report->getDataCBO($_GET['cy']));
			}
	}
	function genHitoryDetail($row,$i,$type,$ar ){
		$html .="<td align='right'>".$i."</td>";
		
		if ($type=='customer'){
		
			$irow=count($ar);
			 
			if ($row['FirstName']=='')
				$html .="<td align='left' style='color:red'>Non-member</td>";
			else 
				$html .="<td align='left'>".$row['FirstName']. "  " .  $row['LastName'] ."</td>";
			$html .="<td align='right'>". number_format( $row['Amount'] ,'2','.',',') ."</td>";
			$html .="<td align='right'>". number_format( $row['Discount'] ,'2','.',',')  ."</td>";
			$html .="<td align='right'>". number_format( $row['TotalNet'] ,'2','.',',')  ."</td>";
			if ($irow>1){
				$html .="<td align='center'><span class='boxTable1'>". $ar[0]['PayType']."</span><span class='boxTable'>".$ar[1]['PayType']."</span></td>";
				$html .="<td align='center'><span class='boxTable1'>". number_format($ar[0]['PaymentAmount'],2,'.',',')."</span><span class='boxTable'>".number_format($ar[1]['PaymentAmount'],2,'.',',')."</span></td>";
			}else{
				$html .="<td align='center'>". $ar[0]['PayType']."</td>";
				$html .="<td align='center'>".number_format($ar[0]['PaymentAmount'],2,'.',',')."</td>";
			}
			$html .="<td align='center'>". number_format( $row['Remain'] ,'2','.',',') ."</td>";
		}else{
			$html .="<td align='left'>".$row['ProductName']."</td>";
			$html .="<td align='center'>".$row['ProductType']."</td>";
			$html .="<td align='right'>". number_format( $row['Amount'] ,'0','.',',')."-". $row['Unit']."</td>";
			$html .="<td align='right'>". number_format( $row['Price'] ,'2','.',',') ."</td>";
			$html .="<td align='right'>". number_format( $row['Discount'] ,'2','.',',')  ."</td>";		
			$html .="<td align='right'>". number_format( $row['total'] ,'2','.',',')  ."</td>";		
		}
		return $html;
	}
	function genHitoryTable($row,$i){
		if ($row['Remain']>0)
			$remain = "<font color=orange>".number_format( $row['Remain'] ,'2','.',',') ."</font>";
		else 
			$remain = number_format( $row['Remain'] ,'2','.',',') ;
			 
		$html .="<td align='right'>".$i."</td>";
	 
		$html .="<td style='display:none'>".$row['SaleDate2']."</td>";
		$html .="<td style='display:none'>".$row['Branch']."</td>";
		$html .="<td align='center' style='display:none'>".$row['BranchName']."</td>";
		$html .="<td align='center'>".$row['SaleDate1']. "</b></td>";
		// by <b><font color='#666'>" .  $row['SaleBy'] ."</font>
		$html .="<td align='right'>". number_format( $row['Amount'] ,'2','.',',') ."</td>";
		$html .="<td align='right'>". number_format( $row['Discount'] ,'2','.',',')  ."</td>";
		$html .="<td align='right'>". number_format( $row['Total'] ,'2','.',',')  ."</td>";
		$html .="<td align='right'>". number_format( $row['Payment'] ,'2','.',',')  ."</td>";
		$html .="<td align='right'>".$remain ."</td>";
		$html .="<td align='center'><img src='images/1530.png' border='0' class='btnViewProduct' style='cursor:pointer'  title='view by product' /></td>";
		$html .="<td align='center'><img src='images/0492.png' border='0' class='btnViewCustomer' style='cursor:pointer' title='view by customer' /></td>";
		
		return $html;
	}
	
 

?>